//
// SoapTrace.Net - A soap message monitoring utility. 
//
// Copyright (C) 2005-2009 Matthew Ward
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Matthew Ward (mrward@users.sourceforge.net)

using SoapTrace.Core.Diagnostics;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using WinPcap;

namespace SoapTrace.Core.Communication
{
	/// <summary>
	/// A SOCK_RAW socket type.
	/// </summary>
	public class RawSocket
	{
		/// <summary>
		/// Raised when an IP packet is received.
		/// </summary>
		public event PacketReceivedEventHandler PacketReceived;
		
		private const int IOC_VENDOR = 0x18000000;
		private const int IOC_IN = -2147483648; 
		private const int SIO_RCVALL = IOC_IN | IOC_VENDOR | 1;
		private const int RCVALL_ON = 1;
		private const int RCVALL_IPLEVEL = 3;
		
		/// <summary>
		/// The socket buffer size.
		/// </summary>
		private const int m_BufferSize = 65535;
		
		/// <summary>
		/// The socket buffer.
		/// </summary>
		private byte[ ] m_Buffer = new byte[ m_BufferSize ];
		
		private Socket m_RawSocket;
		
		/// <summary>
		/// The main processing thread.
		/// </summary>
		private Thread m_Thread;
		
		/// <summary>
		/// Flag indicating whether the main processing thread should
		/// run.
		/// </summary>
		private bool m_Running;
		
		/// <summary>
		/// Socket processing timeout.
		/// </summary>
		private int m_Timeout = 10;
		
		/// <summary>
		/// Creates a new instance of the <see cref="RawSocket"/> class.
		/// </summary>
		public RawSocket( )
		{
		}
		
		/// <summary>
		/// Opens a raw socket on the specified IP address.
		/// </summary>
		/// <param name="address">The IP address.</param>
		public void Open( string address )
		{
			m_RawSocket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP );
			
			IPAddress IPAddress = IPAddress.Parse( address );
			IPEndPoint EndPoint = new IPEndPoint( IPAddress, 0 );
			m_RawSocket.Bind( EndPoint );
			m_RawSocket.IOControl( IOControlCode.ReceiveAll, BitConverter.GetBytes( RCVALL_IPLEVEL ), new byte[ 4 ] );
						
			// Start processing thread.
			StartProcessingThread( );
		}
		
		/// <summary>
		/// Closes the socket.
		/// </summary>
		public void Close( )
		{
			StopProcessingThread( );
			
			if( m_RawSocket != null )
			{
				m_RawSocket.Close( );
				m_RawSocket = null;
			}
		}
		
		/// <summary>
		/// Gets the IP addresses for the local host.
		/// </summary>
		/// <returns></returns>
		public static IPAddress[ ] GetLocalHostIPAddresses( )
		{
			List<IPAddress> addresses = new List<IPAddress>( );
			foreach( IPAddress address in Dns.GetHostAddresses( Dns.GetHostName( ) ) )
			{
				if( address.AddressFamily == AddressFamily.InterNetwork )
				{
					addresses.Add( address );
				}
			}
			return addresses.ToArray( );
		}
		
		/// <summary>
		/// Raises the PacketReceived event.
		/// </summary>
		/// <param name="sender">The event source.</param>
		/// <param name="e">The event arguments.</param>
		protected void OnPacketReceived( object sender, PacketReceivedEventArgs e )
		{
			if( PacketReceived != null )
			{
				PacketReceived( sender, e );
			}
		}
		
		/// <summary>
		/// Starts the main socket processing thread.
		/// </summary>
		private void StartProcessingThread( )
		{
			m_Thread = new Thread( new ThreadStart( ProcessSocket ) );
			m_Running = true;
			m_Thread.Start( );
		}
		
		/// <summary>
		/// Stops the socket processing thread.
		/// </summary>
		private void StopProcessingThread( )
		{
			if( m_Thread != null )
			{
				m_Running = false;
				m_Thread.Join( );
				m_Thread = null;
			}
		}
		
		/// <summary>
		/// Reads data from the raw socket.
		/// </summary>
		private void ProcessSocket( )
		{
			while( m_Running )
			{
				if( IsReadable )
				{					
					// Read the source's response.

					int BytesRead = m_RawSocket.Receive( m_Buffer );

					if( BytesRead > 0 )
					{
						BytesReceived( m_Buffer, BytesRead );
					}
					else
					{
						// Socket has been closed.  Shouldn't happen.
						Logger.LogError( "Raw socket has been closed." );
					} 
				}				
			}
		}
			
		/// <summary>
		/// Gets whether the connection is readable.
		/// </summary>
		private bool IsReadable
		{
			get
			{
				return m_RawSocket.Poll( m_Timeout, SelectMode.SelectRead );
			}
		}
		
		/// <summary>
		/// Bytes received from socket.
		/// </summary>
		/// <param name="bytes">The read bytes.</param>
		/// <param name="amount">The number of bytes read.</param>
		private void BytesReceived( byte[ ] bytes, int amount )
		{
			try
			{
				IPPacket IPPacket = new IPPacket( bytes, 0, amount );
				
				OnPacketReceived( this, new PacketReceivedEventArgs( IPPacket ) );
			}
			catch( Exception Ex )
			{
				Logger.LogError( String.Concat( "RawSocket.BytesReceived. Could not process packet.", Ex.ToString( ) ) );
			}
		}
	}
}
